package com.tanhua.houtai.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.pojo.User;
import com.tanhua.houtai.mapper.AdminMapper;
import com.tanhua.houtai.pojo.Admin;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jdk.nashorn.internal.ir.IfNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Value("${jwt.secret}")
    private String secret;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 登录
     * @param username
     * @param password
     * @param code
     * @param uuid
     * @return
     */
    public Map<String, String> login(String username, String password, String code, String uuid) {

        Map<String, String> result = new HashMap<>();


        //判断是否为空
        if (StrUtil.isEmpty(username) && StrUtil.isEmpty(password) && StrUtil.isEmpty(code)) {
            result.put("error", "数据有空");
            return result;
        }

        //判断账号是否正确
        String regexPhone = "^[1]([3][0-9]{1}|59|58|88|89)[0-9]{8}$";
        Pattern p = Pattern.compile(regexPhone);
        Matcher m = p.matcher(username);



        //判断密码
        String regexpwd = "^.{1,20}$";
        Pattern pp = Pattern.compile(regexpwd);
        Matcher mm = pp.matcher(password);


        //判断验证码是否有效
        String redisKey = "picture_code_" + uuid;
        String recode = this.redisTemplate.opsForValue().get(redisKey);
        if (StrUtil.isEmpty(recode)) {
            result.put("error","验证码失效");
            return result;
        }

        //判断是否登录成功
        if (/*m.matches()&&*/ mm.matches() && recode.equals(code)) {

            password = DigestUtils.md5Hex("123456");
            QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", username).eq("password", password);
            Admin admin = this.adminMapper.selectOne(queryWrapper);


            //生成token
            Map<String, Object> claims = new HashMap<String, Object>();
            claims.put("id", admin.getId());

            // 生成token
            String token = Jwts.builder()
                    .setClaims(claims) //payload，存放数据的位置，不能放置敏感数据，如：密码等
                    .signWith(SignatureAlgorithm.HS256, secret) //设置加密方法和加密盐
                    .setExpiration(new DateTime().plusHours(12).toDate()) //设置过期时间，12小时后过期
                    .compact();

            result.put("token", token);




            //删除Redis中的验证码
            this.redisTemplate.delete(redisKey);
            return result;

        }

        return null;
    }


    /**
     * 用户基本信息
     *
     * @param
     * @return
     */
    public Map<String, Object> profile(String  token) {
        // 通过token解析数据
        Map<String, Object> body = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        Long id = Long.valueOf(body.get("id").toString());
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        Admin admin = this.adminMapper.selectOne(queryWrapper);


        if (null != admin) {

            Map<String, Object> result = new HashMap<>();
            result.put("uid", admin.getId());
            result.put("username", admin.getUsername());
            result.put("avatar", admin.getAvatar());
            return result;
        }
        return null;
    }

    /**
     * 用户登出
     *
     * @return
     */
    public ResponseEntity<Object> logout() {

        return null;
    }

    /**
     * 验证token
     * @param token
     * @return
     */

    public Boolean queryUserByToken(String token) {
        try {
            String[] s = token.split(" ");
            token = s[1];
            // 通过token解析数据
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();

            Long id = Long.valueOf(body.get("id").toString());


            //如果每次都查询数据库，必然会导致性能问题，需要对用户的名称进行缓存操作
            //数据缓存时，需要设置过期时间，过期时间要与token的时间一致

            String redisKey = "TANHUA_HOUTAI_TOKEN_" + id;
            String username = this.redisTemplate.opsForValue().get(redisKey);
            if (StrUtil.isEmpty(username)) {
                Admin admin = this.adminMapper.selectById(id);
                long timeout = Long.valueOf(body.get("exp").toString()) * 1000 - System.currentTimeMillis();
                this.redisTemplate.opsForValue().set(redisKey, admin.getUsername(), timeout, TimeUnit.MILLISECONDS);
                return true;
            }

            return true;

        } catch (ExpiredJwtException e) {
            log.info("token已经过期！ token = " + token);
        } catch (Exception e) {
            log.error("token不合法！ token = " + token, e);
        }
        return false;
    }


}
